<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace form\element\form\traits;

trait File
{
    protected $multiple = false;

    protected $uploadedFile = [];

    /**
     * 上传地址
     * @var string
     */
    protected $url = '';

    protected $accept = '';

    protected $uploadCallback = '';

    protected $ext = [
        '.png', '.jpg', '.jpeg', '.bmp', '.gif'
    ];

    public function ext($ext)
    {
        $this->ext = is_array($ext) ? $ext : [$ext];
        return $this;
    }

    public function url(string $url)
    {
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            throw new \Exception('文件上传地址不是一个标准的链接');
        }
        $this->url = $url;
        return $this;
    }

    public function file($file)
    {
        if (!is_array($file) && !is_string($file)) {
            throw new \Exception('文件参数异常');
        }
        $files = is_array($file) ? $file : [$file];
        unset($file);
        array_map(function ($file) {
            if (strpos($file, 'http') !== false) {
                return true;
            } elseif (!file_exists($file)) {
                throw new \Exception(sprintf('文件%s不存在', $file));
            }
        }, $files);
        $this->uploadedFile = $files;
        return $this;
    }

    public function multiple(bool $multiple = false)
    {
        $this->multiple = $multiple;
        return $this;
    }

    public function accept(string $accept = '')
    {
        $this->accept = $accept;
        return $this;
    }

    public function callback(string $callback = '')
    {
        $this->uploadCallback = $callback;
        return $this;
    }

    protected function getMultiple(): string
    {
        return $this->multiple ? ' multiple ' : '';
    }

    protected function getAccept(): string
    {
        return $this->accept ? 'accept=" ' . $this->accept . ' "' : 'accept=".png,.jpg,.jpeg,.bmp,.gif"';
    }

    protected function getUploadedFile(): string
    {
        return implode(',', $this->uploadedFile);
    }

    protected function getExt(): string
    {
        return 'ext="' . implode(',', $this->ext) . '"';
    }

    protected function getCallback(): string
    {
        if (empty($this->uploadCallback)) {
            return <<<HTML
 lightyear.loading('hide');
                if (res.code === 1) {
                    _this.closest('#file-group_$this->name').find('.file-value').val(res.url);
                } else {
                    lightyear.notify(res.message, 'danger', 3000);
                }
HTML;

        } else {
            return $this->uploadCallback;
        }
    }
}